import numpy
import sys,os,inspect
sys.path.insert(0,os.path.abspath(os.path.join(os.getcwd(), os.pardir)))## add root path 
from KIndicators import KBaseIndicator
import pandas as pd
from KModel.KSingleStock import KSingleStock
from scipy.signal import argrelextrema
import numpy as np
from PyQt4.QtGui import QGraphicsObject,QPen,QBrush,QColor,QPolygonF
from PyQt4 import QtCore,QtGui,Qt
from PyQt4.QtCore import QPointF
from KCharts.KGraphics.KGraphicsSceneSubViewModel import KGraphicsSceneSubViewModel
from KCharts.KGraphics.KBaseDisplayItem import KBaseDisplayItem
from KApp import KConstants as vm
from KAtomIndicators import *
from KTrade.KStockFeed import KStockFeed
class KGartelyHighProb(KBaseIndicator.KBaseIndicator):
	''' moving average related indicators'''
	def __init__(self,parent):

		super(KGartelyHighProb,self).__init__(parent)
		self.windowsize=5 # the size of window to clear weak extremas			
		self.atompeak=KAtomPeak.KAtomPeak(parent)
		self.atompeak.SetWindowSize(self.windowsize)
		self.atompattern=KAtomGartleyPattern.KAtomGartleyPattern(parent,self.atompeak)

		# forward methods to view
		for m in [ 'IsPotentialPatternEnd','GetPatternRetracmentTargetPrice','GetPotentialCPoint']: 
			setattr(self, m, getattr(self.atompattern, m))
			
	def GetPatternList(self):
		return self.atompattern.GetPatternList()	
		
	def GetPeakList(self):
		return self.atompeak.GetPeakList()	
	
	def GetLogicRange(self):
		# get the range of all data in this indicator
		(xr1,yr1)=self.atompeak.GetLogicRange()
		(xr2,yr2)=self.atompattern.GetLogicRange()
		xdatarange=(min(xr1[0],xr2[0]),max(xr1[1],xr2[1]))
		ydatarange=(min(yr1[0],yr2[0]),max(yr1[1],yr2[1]))
		return (xdatarange,ydatarange)
	
	def calculate(self,**kargs):
		

		self.stockfeed=KStockFeed(self.m_stock)
		self.SetupStockFeed(self.stockfeed)		

		#self.peaklist=self.atompeak.calculate()		
		#self.patternlist=self.atompattern.calculate()
		
		
		self.OnStart()
		while self.stockfeed.HasNextBar():
			self.stockfeed.MoveForward()
			self.OnNewBars(self.stockfeed.GetCurrentIndex())		
		self.OnFinish()		

		#print('%d pattern found' %len(self.patternlist))

	## online functions
	def OnNewBars(self,curfeedindex):
		# used in online mode, will be called when a new bar is available
		self.atompeak.OnNewBars(curfeedindex)
		self.atompattern.OnNewBars(curfeedindex)

	def SetupStockFeed(self,feed):
		self.stockfeed=feed
		self.atompeak.SetupStockFeed(self.stockfeed)
		self.atompattern.SetupStockFeed(self.stockfeed)
		
	def OnStart(self):
		# used in online mode, called before simulation started
		
		self.atompeak.OnStart()
		self.atompattern.OnStart()
	
	def OnFinish(self):
		# used in online mode, called after simulation exectued
		self.atompeak.OnFinish()
		self.atompattern.OnFinish()

		
		KBaseIndicator.KBaseIndicator.update(self)# update data after calcuation
		
class KGartelyHighProbDisplayItem(KBaseIndicator.KBaseIndicatorDisplayItem):
	
	def __init__(self,viewmodel,stockobj):
		KBaseIndicator.KBaseIndicatorDisplayItem.__init__(self,viewmodel,stockobj)
		
		self.peakdispitem=KAtomPeak.KAtomPeakDisplayItem(viewmodel,stockobj)
		#self.peakdispitem.setParentItem(self) # so that child display item get automatically called when parent repaint, this introduce buy when remove item	
		
		self.cminerdispitem=KAtomGartleyPattern.KAtomGartleyPatternDisplayItem(viewmodel,stockobj)
		#self.cminerdispitem.setParentItem(self)# so that child display item get automatically called when parent repaint	
		
		# create sub display items
		
	def SetModel(self,model):
		# set the model used to perform calcuation
		self.model=model
		self.peakdispitem.SetModel(model.atompeak)
		self.cminerdispitem.SetModel(model.atompattern)

		
	def PrepareRenderPicture(self):
		## pre-computing a QPicture object allows paint() to run much more quickly, 
		## rather than re-drawing the shapes every time.
		
		try:
			if not hasattr(self,'model') :
					return
			if not self.model.IsReady():
				return 		
			if self.model.IsResultExpired()==True:
				self.model.calculate()	
					
			self.picture = QtGui.QPicture()
			painter = QtGui.QPainter(self.picture)	
	
			self.peakdispitem.PaintPeak(painter)
			self.cminerdispitem.PaintPattern(painter)
			painter.end()	
		except:
			print('faild to render KGartelyHighProb')		
		
	
if __name__ == "__main__":
		m_stock=KSingleStock() # create its stock object
		m_stock.SetTick('us','nasdaq','aapl')	
		
		eindicator=KGartelyHighProb(m_stock)
		eindicator.calculate()
	